<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="雷达选择" prop="radar">
        <el-select v-model="selectedRadar" placeholder="请选择雷达" @change="handleRadarChange">
          <el-option
            v-for="radar in radarOptions"
            :key="radar.value"
            :label="radar.label"
            :value="radar.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="模式选择" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择模式" clearable>
          <el-option label="PPI模式" value="PPI" />
          <el-option label="DBS模式" value="DBS" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="时间" prop="timeParam">
        <TimeSelector
          v-model="queryParams.timeParam"
          :show-pagination="true"
          :default-page-size="20"
          :city="selectedCity"
          placeholder="请选择时间"
          width="260px"
          @change="handleTimeChange"
          @load-complete="handleTimeLoadComplete"
          ref="timeSelectorRef"
        />
      </el-form-item>
      <el-form-item v-if="queryParams.type === 'PPI'" label="X坐标范围" prop="xCoordinateRange">
        <div style="display: flex; align-items: center; gap: 8px;">
          <el-input-number 
            v-model="queryParams.xCoordinateMin" 
            :precision="6" 
            :controls="false" 
            placeholder="最小值" 
            style="width: 120px" 
          />
          <span style="color: #909399;">至</span>
          <el-input-number 
            v-model="queryParams.xCoordinateMax" 
            :precision="6" 
            :controls="false" 
            placeholder="最大值" 
            style="width: 120px" 
          />
        </div>
      </el-form-item>
      <el-form-item v-if="queryParams.type === 'PPI'" label="Y坐标范围" prop="yCoordinateRange">
        <div style="display: flex; align-items: center; gap: 8px;">
          <el-input-number 
            v-model="queryParams.yCoordinateMin" 
            :precision="6" 
            :controls="false" 
            placeholder="最小值" 
            style="width: 120px" 
          />
          <span style="color: #909399;">至</span>
          <el-input-number 
            v-model="queryParams.yCoordinateMax" 
            :precision="6" 
            :controls="false" 
            placeholder="最大值" 
            style="width: 120px" 
          />
        </div>
      </el-form-item>
      <el-form-item label="最大风速" prop="windSpeedLike">
        <el-input-number v-model="queryParams.windSpeedLike" :precision="2" :controls="false" placeholder="请输入风速" style="width: 160px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
        <el-button type="warning" icon="setting" @click="handleConfig">配置</el-button>
        <el-button icon="refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['monitor:logininfor:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="delete" @click="handleClean" v-hasPermi="['monitor:logininfor:remove']">清空</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="download" @click="handleExport" v-hasPermi="['system:logininfor:export']">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" border @selection-change="handleSelectionChange" size="small">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="100" />
      <!-- <el-table-column label="ID" align="center" prop="id" width="80" /> -->
      <el-table-column label="数据来源表" align="center" prop="sourceTable" min-width="200" />
      
      <!-- DBS模式显示的列 -->
      <template v-if="queryParams.type === 'DBS'">
        <el-table-column label="高度" align="center" prop="height" />
        <el-table-column label="风向" align="center" prop="windDirection" />
        <el-table-column label="风速" align="center" prop="windSpeed" />
        <el-table-column label="垂直风速" align="center" prop="verticalSpeed" />
      </template>
      
      <!-- PPI模式显示的列 -->
      <template v-if="queryParams.type === 'PPI'">
        <el-table-column label="X坐标" align="center" prop="xCoordinate" />
        <el-table-column label="Y坐标" align="center" prop="yCoordinate" />
        <el-table-column label="风速" align="center" prop="windSpeed" />
        <el-table-column label="风向" align="center" prop="windDirection" />
      </template>
      
      <!-- <el-table-column label="操作" width="100" align="center">
        <template #default="scope">
          <el-button type="danger" text plain icon="delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 报警配置弹窗 -->
    <el-dialog
      v-model="configDialogVisible"
      title="报警配置"
      width="400px"
      :before-close="handleConfigClose"
    >
      <el-form
        ref="configFormRef"
        :model="configForm"
        :rules="configRules"
        label-width="120px"
      >
        <el-form-item label="风速预警最大值" prop="max">
          <el-input-number
            v-model="configForm.max"
            :precision="2"
            style="width: 100%"
            placeholder="请输入最大值"
          />
        </el-form-item>
        <!-- <el-form-item label="最小值" prop="min">
          <el-input-number
            v-model="configForm.min"
            :precision="2"
            style="width: 100%"
            placeholder="请输入最小值"
          />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleConfigClose">取消</el-button>
          <el-button type="primary" @click="handleConfigSubmit" :loading="configSubmitLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="logininfor">
import { onMounted, onBeforeUnmount, computed } from 'vue'
import { list as queryList, delLogininfor, cleanLogininfor, exportLogininfor } from '@/api/monitor/logininfor'
import { showTime } from '@/utils'
import {
  tableQuery,
  windDataDBS,
  windDataPPI,
  getConfig,
  putConfig,
  alarmRecord
} from '@/api/system/user'
import TimeSelector from '@/components/TimeSelector/index.vue'
// 遮罩层
const loading = ref(false)
// 选中数组
const ids = ref([])
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 表格数据
const list = ref([])
// 状态数据字典
const statusOptions = ref([])
// 时间选项数据
const timeOptions = ref([])
// 日期范围
const dateRange = ref([])
// 雷达选择
const selectedRadar = ref('32.390648,117.050972') // 默认合肥站
// 雷达选项配置，包含坐标和对应的城市代码
const radarOptions = ref([
  { label: '合肥站', value: '32.390648,117.050972', city: 'hefei' },
  { label: '宣城站', value: '30.851,119.009', city: 'xuancheng' },
])
// 配置弹窗相关
const configDialogVisible = ref(false)
const configFormRef = ref()
const configSubmitLoading = ref(false)
const configForm = reactive({
  id: 0,
  max: null,
  min: null
})
const configRules = {
  max: [
    { required: true, message: '请输入最大值', trigger: 'blur' }
  ],
  min: [
    { required: true, message: '请输入最小值', trigger: 'blur' }
  ]
}
// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  type: 'PPI',
  city: 'hefei', // 默认合肥，根据雷达选择动态更新
  timeParam: undefined,
  ipaddr: undefined,
  userName: undefined,
  status: undefined,
  max: undefined,
  min: undefined,
  // X坐标范围
  xCoordinateMin: undefined,
  xCoordinateMax: undefined,
  // Y坐标范围
  yCoordinateMin: undefined,
  yCoordinateMax: undefined,
  windSpeedLike: undefined,
})

const { proxy } = getCurrentInstance()

// 根据 selectedRadar 计算对应的城市
const selectedCity = computed(() => {
  const currentRadar = radarOptions.value.find(r => r.value === selectedRadar.value)
  return currentRadar?.city || ''
})

/** 获取时间选项数据 */
async function getTimeOptions() {
  try {
    const response = await tableQuery({
      pageNum: 1,
      pageSize: 100,
      type: 'PPI',
      city: queryParams.city, // 添加城市参数
    })
    if (response.code === 200) {
      timeOptions.value = response.data.result || []
      // 如果有数据且当前没有选择时间，自动选择第一个
      if (timeOptions.value.length > 0 && !queryParams.timeParam) {
        queryParams.timeParam = timeOptions.value[0].dateTimeString
        // 自动选择第一个时间后，获取对应的数据
        getDataConfig()
      }
    }
  } catch (error) {
    console.error('获取时间选项失败:', error)
    timeOptions.value = []
  }
}

/** 查询数据列表 */
async function getList() {
  if (!queryParams.type || !queryParams.timeParam) {
    console.warn('请选择模式和时间')
    return
  }
  
  loading.value = true
  
  try {
    const paramsRaw = {
      timeParam: queryParams.timeParam,
      city: queryParams.city, // 添加城市参数
      pageNum: queryParams.pageNum,
      pageSize: 10,
      max: configForm.max,
      min: configForm.min,
      // X坐标范围参数
      xCoordinateMin: queryParams.xCoordinateMin,
      xCoordinateMax: queryParams.xCoordinateMax,
      // Y坐标范围参数
      yCoordinateMin: queryParams.yCoordinateMin,
      yCoordinateMax: queryParams.yCoordinateMax,
      windSpeedLike: queryParams.windSpeedLike,
      useLike: queryParams.windSpeedLike ? true : false
    }
    let response = await alarmRecord(paramsRaw)
 
    
    if (response.code === 200) {
      // 处理返回的数据，确保字段名正确映射
      const rawData = response.data.result || []
      list.value = rawData.map(item => ({
        id: item.id,
        sourceTable: item.sourceTable,
        // DBS模式字段
        height: item.height,
        windDirection: item.windDirection,
        windSpeed: item.windSpeed,
        verticalSpeed: item.verticalSpeed,
        // PPI模式字段
        xCoordinate: item.xCoordinate,
        yCoordinate: item.yCoordinate
      }))
      total.value = response.data.totalNum || 0
    } else {
      list.value = []
      total.value = 0
      proxy.$modal.msgError(response.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    list.value = []
    total.value = 0
    proxy.$modal.msgError('获取数据失败')
  } finally {
    loading.value = false
  }
}
// 登录状态字典翻译
function statusFormat(row, column) {
  return proxy.selectDictLabel(statusOptions.value, row.status)
}

// TimeSelector 事件处理函数
const timeSelectorRef = ref()

// 处理时间选择变化
const handleTimeChange = (value) => {
  console.log('时间选择变化:', value)
  // 时间改变时重新获取数据
  if (value && queryParams.type) {
    getList()
  }
}

// 处理时间数据加载完成
const handleTimeLoadComplete = (timeOptions) => {
  console.log('时间数据加载完成，共', timeOptions.length, '个选项')
  // 可以在这里添加额外的处理逻辑
}
// 监听模式选择变化
watch(() => queryParams.type, (newType) => {
  if (newType) {
    // 清空当前时间选择
    queryParams.timeParam = undefined
    // 重新获取时间选项
    getTimeOptions()
  }
}, { immediate: true })

// 监听时间选择变化
watch(() => queryParams.timeParam, (newTimeParam) => {
  if (newTimeParam && queryParams.type) {
    // 时间改变时重新获取数据
    
  }
})

// 监听城市变化，重新获取时间选项和数据
watch(() => queryParams.city, (newCity) => {
  if (newCity && queryParams.type) {
    // 城市改变时，清空当前时间选择，重新获取时间选项
    queryParams.timeParam = undefined
    // TimeSelector 会自动重新加载数据
    if (timeSelectorRef.value) {
      timeSelectorRef.value.refresh()
    }
  }
})

// 监听本地雷达选择变化
watch(selectedRadar, (newValue) => {
  handleRadarChange(newValue)
})

// 处理雷达选择变化（本地选择）
function handleRadarChange(value) {
  const currentRadar = radarOptions.value.find(r => r.value === value)
  if (currentRadar && currentRadar.city) {
    queryParams.city = currentRadar.city
    console.log('雷达选择变化，城市更新为:', currentRadar.city)
  }
}

// 处理雷达选择事件（来自 DeviceStatus 组件）
function handleRadarSelected(event) {
  const { city } = event.detail
  if (city && (city === 'hefei' || city === 'xuancheng')) {
    queryParams.city = city
    // 同步更新本地选择的雷达
    const radar = radarOptions.value.find(r => r.city === city)
    if (radar) {
      selectedRadar.value = radar.value
    }
    console.log('雷达选择变化（来自DeviceStatus），城市更新为:', city)
  }
}

proxy.getDicts('sys_common_status').then((response) => {
  statusOptions.value = response.data
})

// 页面加载时执行配置获取
onMounted(() => {
  // 监听雷达选择事件（来自 DeviceStatus 组件）
  window.addEventListener('radar-selected', handleRadarSelected)
  
  // 初始化：根据默认选择的雷达设置城市
  handleRadarChange(selectedRadar.value)
})

// 组件卸载时移除事件监听
onBeforeUnmount(() => {
  window.removeEventListener('radar-selected', handleRadarSelected)
})

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  
  // 手动重置查询参数
  queryParams.pageNum = 1
  queryParams.pageSize = 10
  queryParams.type = 'PPI'
  queryParams.timeParam = undefined
  queryParams.ipaddr = undefined
  queryParams.userName = undefined
  queryParams.status = undefined
  queryParams.max = undefined
  queryParams.min = undefined
  // 重置坐标范围参数
  queryParams.xCoordinateMin = undefined
  queryParams.xCoordinateMax = undefined
  queryParams.yCoordinateMin = undefined
  queryParams.yCoordinateMax = undefined
  queryParams.windSpeedLike = undefined
  
  // 重置表单
  proxy.resetForm('queryForm')
  
  // 重置时间选择器
  if (timeSelectorRef.value) {
    timeSelectorRef.value.clearTimeFilter()
  }
  
  // 重置后重新获取时间选项
  getTimeOptions()
  handleQuery()
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.infoId)
  multiple.value = !selection.length
}
/** 删除按钮操作 */
function handleDelete(row) {
  const infoIds = row.infoId || ids.value
  proxy
    .$confirm('是否确认删除访问编号为"' + infoIds + '"的数据项?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(function () {
      return delLogininfor(infoIds)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
}
/** 清空按钮操作 */
function handleClean() {
  proxy
    .$confirm('是否确认清空所有登录日志数据项?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(function () {
      return cleanLogininfor()
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('清空成功')
    })
}
/** 导出按钮操作 */
function handleExport() {
  proxy
    .$confirm('是否确认导出所有操作日志数据项?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(function () {
      return exportLogininfor(queryParams)
    })
    .then((response) => {
      proxy.download(response.data.path)
    })
}
async function getDataConfig() { 
  const response = await getConfig()
    if (response.code === 200) {
      // 填充配置表单数据
      Object.assign(configForm, response.data)
      getList()
    } else {
      proxy.$modal.msgError(response.msg || '获取配置失败')
    }
}
/** 配置按钮操作 */
async function handleConfig() {
  try {
    // 重置查询参数
    queryParams.pageNum = 1
    queryParams.pageSize = 10
    queryParams.type = 'PPI'
    queryParams.timeParam = undefined
    queryParams.ipaddr = undefined
    queryParams.userName = undefined
    queryParams.status = undefined
    queryParams.max = undefined
    queryParams.min = undefined
    // 重置坐标范围参数
    queryParams.xCoordinateMin = undefined
    queryParams.xCoordinateMax = undefined
    queryParams.yCoordinateMin = undefined
    queryParams.yCoordinateMax = undefined
    queryParams.windSpeedLike = undefined
    
    // 重新获取时间选项
    await getTimeOptions()
    
    // 获取配置数据
    configDialogVisible.value = true
    // getList()
  } catch (error) {
    console.error('获取配置失败:', error)
    proxy.$modal.msgError('获取配置失败')
  }
}

/** 配置弹窗关闭 */
function handleConfigClose() {
  configDialogVisible.value = false
  // 重置表单
  if (configFormRef.value) {
    configFormRef.value.resetFields()
  }
}

/** 配置提交 */
async function handleConfigSubmit() {
  if (!configFormRef.value) return
  
  try {
    await configFormRef.value.validate()
    configSubmitLoading.value = true
    
    const response = await putConfig(configForm)
    if (response.code === 200) {
      proxy.$modal.msgSuccess('配置保存成功')
      configDialogVisible.value = false
      getList()
    } else {
      proxy.$modal.msgError(response.msg || '配置保存失败')
    }
  } catch (error) {
    if (error !== false) { // 不是表单验证错误
      console.error('配置保存失败:', error)
      proxy.$modal.msgError('配置保存失败')
    }
  } finally {
    configSubmitLoading.value = false
  }
}
</script>

<style scoped lang="scss">
:deep(.el-table) {
  .el-table__row {
    height: 40px;
  }
  
  .el-table__cell {
    padding: 6px 8px;
  }
  
  .el-table__header {
    th {
      height: 40px;
      padding: 6px 8px;
    }
  }
}

// TimeSelector 组件样式 - 与 Element UI 默认样式保持一致
:deep(.time-selector) {
  .el-button {
    background: #ffffff !important;
    border: 1px solid #dcdfe6 !important;
    color: #606266 !important;
    border-radius: 6px;
    
    &:hover {
      background: #ecf5ff !important;
      border-color: #c6e2ff !important;
      color: #409eff !important;
    }
    
    &:focus {
      background: #ecf5ff !important;
      border-color: #c6e2ff !important;
      color: #409eff !important;
    }
    
    &.is-active {
      background: #409eff !important;
      border-color: #409eff !important;
      color: #ffffff !important;
    }
  }
  
  .el-input__wrapper {
    background: #ffffff !important;
    border: 1px solid #dcdfe6 !important;
    border-radius: 6px;
    
    &:hover {
      border-color: #c0c4cc !important;
    }
    
    &.is-focus {
      border-color: #409eff !important;
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2) !important;
    }
    
    .el-input__inner {
      color: #606266 !important;
      
      &::placeholder {
        color: #c0c4cc !important;
      }
    }
    
    .el-input__suffix {
      .el-input__suffix-inner {
        color: #c0c4cc !important;
      }
    }
  }
}
</style>
